from fastapi import APIRouter, Query, Depends

from application.utils import get_rich_logger
from authentication.jwt import get_current_user
from cluster.clusters import add_new_cluster_record, view_cluster_status_information, update_cluster_info_record, \
    delete_cluster_record
from domain.authentication import User
from domain.cluster import ClusterInfo, ClusterInDB

logger = get_rich_logger()

cluster_router = APIRouter(
    prefix="/cluster",
    tags=['cluster']
)


@cluster_router.post("/create")
async def register_new_cluster(
        cluster: ClusterInfo,
        current_user: User = Depends(get_current_user)
):
    cluster_info_in_db = ClusterInDB(
        name=cluster.name,
        uuid=current_user.uuid.hex,
        cluster_info=cluster.json()
    )
    logger.debug(f"New cluster info: {cluster_info_in_db}")
    new_record_response = await add_new_cluster_record(
        new_cluster_record=cluster_info_in_db,
        user=current_user
    )
    return new_record_response


@cluster_router.get("/fetch")
async def get_cluster_status(
        cluster_record_id: str | None = Query(
            default=None,
            alias="cluster-record-id",
            title="Target Cluster record id.",
            description="The Cluster intended to get status & condition about.",
        ),
        current_user: User = Depends(get_current_user)
):
    metadata_record = await view_cluster_status_information(
        target_cluster_id=cluster_record_id,
        user=current_user
    )
    return metadata_record


@cluster_router.patch("/update")
async def update_cluster_info(
        new_cluster: ClusterInfo,
        cluster_record_id: str = Query(
            ...,
            alias="cluster-record-id",
            title="Target Cluster record id.",
            description="The Cluster intended to be updated.",
        ),
        current_user: User = Depends(get_current_user)
):
    updated_record = await update_cluster_info_record(
        user=current_user,
        update_record_id=cluster_record_id,
        updated_cluster_info=new_cluster
    )
    return updated_record


@cluster_router.delete("/delete")
async def delete_registered_cluster(
        cluster_record_id: str = Query(
            ...,
            alias="cluster-record-id",
            title="Target Cluster record id.",
            description="The Cluster intended to be deleted.",
        ),
        current_user: User = Depends(get_current_user)
):
    ret = await delete_cluster_record(
        target_cluster_record=cluster_record_id,
        user=current_user
    )
    return ret
